﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace DapperDemo.Api
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new {id = RouteParameter.Optional}
                );


            //自定义 webapi 处理日期时间类型数据转换器
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new JSONDateTimeJsonConverter());
        }

        /// <summary>
        /// 时间类型格式转化
        /// </summary>
        public class JSONDateTimeJsonConverter : DateTimeConverterBase
        {
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                JsonSerializer serializer)
            {
                if (reader.Value == null)
                    return DateTime.MinValue;

                return (DateTime) reader.Value;
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                DateTime date = (DateTime) value;
                if (date != DateTime.MinValue)
                {
                    writer.WriteValue(date.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
                }
                else
                {
                    writer.WriteRawValue("null");
                }
            }
        }
    }
}
